<template>
  <a-select
      show-search
      allowClear
      v-bind="$attrs" 
      v-on="$listeners"
      v-model="currentValue"
      :placeholder="placeholder"
      option-filter-prop="children"
      :filter-option="filterOption"
      @focus="handleFocus"
      @blur="handleBlur"
      @change="handleChange"
    >
      <a-icon v-if="fetching" style="color: #096dd9" slot="suffixIcon" type="loading" />
      <a-spin v-if="fetching" slot="notFoundContent" size="small" />
      <a-select-option v-for="(item, index) in dataList" :value="item[replaceFields.value]">
        {{item[replaceFields.name]}}
      </a-select-option>
    </a-select>
</template>

<script>
  export default {
    name:'a'+ Date.now(),
    // name: 'BaseSelect',
    props: {
      // v-model绑定的数据
      value: {
        type: [Array, String, Object, undefined],
        default() {
          return undefined
        }
      },
      placeholder: {
        type: String,
        default () {
          return '请选择'
        }
      },
      datas: {
        type: Array,
        default() {
          return []
        }
      },
      loadData: {
        type: [Function, null],
        default: null
      },
      replaceFields: {
        type: Object,
        default() {
            return { value: 'id', name: 'name' }
        },
      }
    },
    computed: {
      dataList() {
        return this.loadData !== null ? this.list : this.datas;
      },
      currentValue: {
        get: function () {
          return this.value ? this.value : undefined
        },
        set: function (value) {
          this.$emit('input', value)
          // this.$emit(
          //   'update:option',
          //   this.list.find((item) => item.id === value)
          // )
          // this.$emit(
          //   'getOption',
          //   this.list.find((item) => item.id === value)
          // )
        }
      }
    },
    data() {
        return {
          fetching: false,
          list: []
        }
    },
    mounted() {
      console.log(this.loadData)
      if (this.loadData) {
        this.fetching = true;
        this.loadData().then((res) => {
          this.fetching = false;
          if (res && res.code == 200) {
            this.list = res.data;
          }
        })
      }
      // console.log(this.loadData)
    },
    methods: {
      handleChange(value) {
        console.log(`selected ${value}`);
      },
      handleBlur() {
        console.log('blur');
      },
      handleFocus() {
        console.log('focus');
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
    },
  };
</script>

<style>
</style>
